/**
 * @file adc.c
 * @author LuoJing
 * @version 1.0
 * @date 2018-09-14
 * @brief YC adc api
 * @details Read the voltage value
 */
 
#include "include.h"
#include "adc.h"
#include "uart.h"

#pragma location=mem_0_5_adc_io_data
__no_init Adc_CalibrationVal StandardVol;

 u16_t YC_calculate_adc(AdcType  io_num, s16_t CurrAdcVal);
 
u16_t YC_get_adc(AdcType  io_num)
{

	if(io_num ==  ADC_CONFIG_VINLPM){
		REG8(RF_ADC_MODE) = 0xbf;	
		
	} else if(io_num ==  ADC_CONFIG_HVIN){
		REG8(RF_ADC_MODE) = 0xaf;
		
	} else {
		REG8(RF_ADC_MODE) = 0x8f;
		REG8(RF_ADC_CH) = io_num;
	}
	BitSet(ADDR_REG_UART_BAUD+1, 7);
	REG8(RF_ADC_CH) |= 0x30;
	REG8_WRITE(RFEN_ADC, 0x7c);
	REG8_WRITE(RF_ADC_GC, 0xaa);
	delayms(1);
	BitClr(ADDR_REG_UART_BAUD+1, 7);
	return YC_calculate_adc(io_num,REGS16(CORE_ADC_SUM));
}


static u16_t YC_calculate_adc(AdcType  io_num, s16_t CurrAdcVal)
{	
	if(io_num ==  ADC_CONFIG_VINLPM) {		
		return ((((s32_t)CurrAdcVal - StandardVol.Vinlpm_2v_data)*100) / \
			    (StandardVol.Vinlpm_3v_data - StandardVol.Vinlpm_2v_data)  + 200);			   
	}
	else if(io_num ==  ADC_CONFIG_HVIN) {
		return ((((s32_t)CurrAdcVal - StandardVol.hvin_1v_data)*400) / \
			    (StandardVol.hvin_5v_data - StandardVol.hvin_1v_data)  + 100);
	}
	else {
		return ((((s32_t)CurrAdcVal - StandardVol.io_0_5v_data)*50) / \
				 (StandardVol.io_1v_data - StandardVol.io_0_5v_data)  + 50);		   		    
	}
}
